package com.net.xpay.common.validator;

import com.google.common.base.Strings;
import com.net.xpay.common.domain.CheckCode;
import com.net.xpay.common.domain.operator.OperatorUser;
import com.net.xpay.common.enums.user.CheckCodeType;
import com.net.xpay.common.manager.CheckCodeManager;
import com.net.xpay.common.model.RegisterOperatorUserModel;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.common.exception.BusinessException;
import com.net.common.util.PhoneUtil;
import com.net.xpay.common.manager.operator.OperatorUserManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户签约参数验证
 */
@Slf4j
@Component
public class RegisterOperatorUserValidator {
    private static final int MAX_PASS_LENGTH = 20; //最大的密码长度
    private static final int MIN_PASS_LENGTH = 6; //最小的密码长度

    @Autowired
    private CheckCodeManager checkCodeManager;

    @Autowired
    private CheckCodeValidator checkCodeValidator;

    @Autowired
    private OperatorUserManager operatorUserManager;


    public void validateRegisterOperatorUser(RegisterOperatorUserModel model) {
        if (Strings.isNullOrEmpty(model.getMobile())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请输入手机号");
        }
        //验证手机号
        if (!PhoneUtil.isEffectiveMobile(model.getMobile())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "手机号格式不正确");
        }

        if (Strings.isNullOrEmpty(model.getPassword())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请输入密码");
        }
        if (model.getPassword().length() > MAX_PASS_LENGTH || model.getPassword().length() < MIN_PASS_LENGTH) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "密码长度必须在6到20个字符");
        }
        if (Strings.isNullOrEmpty(model.getCheckCode())){
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请输入验证码");
        }

        //验证验证码
        CheckCode checkCode = checkCodeManager.findByMobileAndType(model.getMobile(), CheckCodeType.OPERATOR_USER_REGISTER);
        checkCodeValidator.validateCheckCode(checkCode, model.getCheckCode());


        OperatorUser operatorUser = operatorUserManager.findByMobile(model.getMobile());
        if (operatorUser != null){
            throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "用户已经注册，请勿重复注册");
        }
    }
}
